package jafou.server;

import jafou.Model.Forum;
import jafou.Model.JaFouUser;
import jafou.Model.PMF;
import jafou.Model.Topic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * Put all application wide settings here
 * 
 * @author NipunKumar
 * 
 */
public class JafouEnv {
	public static final String _DEFAULT_SKIN = "default";

	JaFouUser getCurrentUser() {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null) {
			return null;
		} else {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				String query = "select from " + JaFouUser.class.getName()
						+ " where email == \"" + user.getEmail() + "\"";
				List<JaFouUser> l = (List<JaFouUser>) pm.newQuery(query)
						.execute();
				if (l.size() > 0) {
					return l.get(0);
				} else {
					JaFouUser jUser = new JaFouUser(user);
					pm.makePersistent(jUser);
					return jUser;
				}
			} finally {
				pm.close();
			}
		}
	}
	
	HashMap<String, String> getUserAttributes() {
		UserService userService = UserServiceFactory.getUserService();
		HashMap<String, String> map = new HashMap<String, String>();
		JaFouUser user = getCurrentUser();
		if(user != null) {
			map.put("logged_in", "true");
			map.put("id", "" + user.getId());
			map.put("username", user.getName());
			boolean admin = userService.isUserAdmin();
			map.put("is_admin", admin?"true":"false");
			map.put("logout_url", userService.createLogoutURL("/"));
		} else {
			map.put("logged_in", "false");
			map.put("login_url", userService.createLoginURL("/"));
		}
		return map;
	}
	
	String getUserNameFromId(String userId)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			JaFouUser user = pm.getObjectById(JaFouUser.class, Long.parseLong(userId));
			if(user.getName() != null) {
				return user.getName();
			} else if (user.getEmail() != null) {
				return user.getEmail();
			}
		} finally {
			pm.close();
		}
		return "anonymous";
	}
}
